﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CurriculumnManage.DBAccess;
using System.Configuration;
using CurriculumnManage.Helper;
using System.IO;
using System.Net.Mail;

namespace CurriculumnManage
{
    public partial class frmMail : Form
    {
        private int? iNendo;
        private int? iGrade;
        private string ScoreType;
        private string mondaiid;
        private string mondaiNO;
        private string subject;

        public string address;
        public string teacher;

        private string kaitouRitu;
        private string mondaiSrc;
        private string vGaki;
        private int iGaki;

        public string PublicStartDate;
        public string PublicEndDate;
        private string AttachFile;
        public frmMail()
        {
            InitializeComponent();
        }

        public void setMondaiInfo(int nendo, int grade, string iSubjectGradeProfileId, string subjectName, string vTeacher, string mailAddress)
        {
            this.iNendo = nendo;
            this.iGrade = grade;
            this.mondaiid = iSubjectGradeProfileId;
            this.subject = subjectName;
            this.teacher = vTeacher;
            this.address = mailAddress;
        }
        private void btnSelectAddress_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(mondaiid)) return;
                frmMailAddress mailAddress = new frmMailAddress(this);
                mailAddress.iSubjectGradeProfileID = mondaiid;
                mailAddress.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonFunction.ShowError("frmMail.btnSelectAddress_Click", ex.Message);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnSend.Enabled = false;
                string ssl = CommonFunction.GetInitValueByKey("SmtpSSL");
                if (ssl == "1")
                    sendMailSSL();
                else
                    sendMail();
                this.btnSend.Enabled = true;
            }
            catch (Exception ex)
            {
                CommonFunction.ShowError("frmMail.btnSend_Click", ex.Message);
            }
        }

        private System.Web.Mail.MailPriority GetWebMailPriority(int selectIndex)
        {
            if (selectIndex == 0) return System.Web.Mail.MailPriority.Normal;
            else if (selectIndex == 1) return System.Web.Mail.MailPriority.Low;
            else if (selectIndex == 2) return System.Web.Mail.MailPriority.High;
            return System.Web.Mail.MailPriority.Normal;
        }

        private MailPriority GetNetMailPriority(int selectIndex)
        {
            if (selectIndex == 0) return MailPriority.Normal;
            else if (selectIndex == 1) return MailPriority.Low;
            else if (selectIndex == 2) return MailPriority.High;
            return MailPriority.Normal;
        }

        private void sendMailSSL()
        {
            try
            {
                string host = CommonFunction.GetInitValueByKey("SmtpHost");

                if (string.IsNullOrEmpty(host))
                {
                    CommonFunction.ShowMsg("メールサーバは取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpHost未設定");
                    return;
                }
                string port = CommonFunction.GetInitValueByKey("SmtpPort");

                string ssl = CommonFunction.GetInitValueByKey("SmtpSSL");
                if (string.IsNullOrEmpty(ssl)) ssl = "";

                string ReplyTo = CommonFunction.GetInitValueByKey("ReplyTo");
                if (string.IsNullOrEmpty(ReplyTo)) ReplyTo = "";

                string user = CommonFunction.GetInitValueByKey("SmtpUser");
                string pwd = CommonFunction.GetInitValueByKey("SmtpPwd");

                if (string.IsNullOrEmpty(user))
                {
                    CommonFunction.ShowMsg("送信者情報は取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpUser未設定");
                    return;
                }
                string mailFrom = CommonFunction.GetInitValueByKey("SmtpFrom");
                if (string.IsNullOrEmpty(mailFrom))
                {
                    CommonFunction.ShowMsg("送信者情報は取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpFrom未設定");
                    return;
                }
                string body = txtBody.Text;
                if (string.IsNullOrEmpty(body))
                {
                    CommonFunction.ShowMsg("送信者内容を入力してください。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:txtBody未入力");
                    return;
                }
                string mailTo = txtAddr.Text.Trim();

                if (string.IsNullOrEmpty(mailTo))
                {
                    CommonFunction.ShowMsg("宛先を入力してください。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:txtAddr未入力");
                    return;
                }

                string mailCC = txtCC.Text.Trim();
                if (string.IsNullOrEmpty(mailCC))
                {
                    mailCC = "";
                }

                System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
                // string mail As New System.Web.Mail.MailMessage()
                string subject = txtSubject.Text.Trim();

                if (string.IsNullOrEmpty(subject))
                    mail.Subject = "教育指針について";
                else
                    mail.Subject = subject;


                //メールの文字コードを設定
                string encode = CommonFunction.GetInitValueByKey("MailEncode");

                if (!string.IsNullOrEmpty(encode))
                    mail.BodyEncoding = System.Text.Encoding.GetEncoding(encode);
                else

                    mail.BodyEncoding = System.Text.Encoding.GetEncoding("iso-2022-jp");


                //送信者設定

                mail.From = mailFrom;

                if (cmbPriority.Text == "")
                    mail.Priority = System.Web.Mail.MailPriority.Normal;
                else
                    mail.Priority = GetWebMailPriority(cmbPriority.SelectedIndex);


                mail.Body = body;

                mail.To = mailTo;
                if (!string.IsNullOrEmpty(this.lblFileName.Text))
                {
                    if (!string.IsNullOrEmpty(AttachFile))
                        mail.Attachments.Add(new System.Web.Mail.MailAttachment(AttachFile));
                }
                if (!string.IsNullOrEmpty(mailCC))
                    //mail.Cc = mailCC;
                    mail.Bcc = mailCC;



                //smtpauthenticateを使う時は必ず2にする
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);//sendusingを2にした時は、必ずサーバーとポートを指定する
                //SMTPサーバーを指定
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", host);//ptnsmtp.mail.yahoo.co.jp
                //ポート番号を指定する
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port);//465

                //認証を使う
                //1はbasic認証、2はNTLM認証
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
                //ユーザー名
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", user);
                //パスワード
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pwd);
                if (ssl == "1")
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

                System.Web.Mail.SmtpMail.SmtpServer = host;

                //メールを送信
                System.Web.Mail.SmtpMail.Send(mail);

                //メール送信状態更新
                //updateStatus(mondaiid, 1, teacher, address, "");

                this.Close();

            }
            catch (Exception ex)
            {
                CommonFunction.ShowError("frmMail.sendMailSSL", ex.Message);
            }
        }

        private void sendMail()
        {
            try
            {

                string host = CommonFunction.GetInitValueByKey("SmtpHost");

                if (string.IsNullOrEmpty(host))
                {
                    CommonFunction.ShowMsg("メールサーバは取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpHost未設定");
                    return;
                }

                string port = CommonFunction.GetInitValueByKey("SmtpPort");

                string ssl = CommonFunction.GetInitValueByKey("SmtpSSL");
                if (string.IsNullOrEmpty(ssl)) ssl = "";

                string ReplyTo = CommonFunction.GetInitValueByKey("ReplyTo");
                if (string.IsNullOrEmpty(ReplyTo)) ReplyTo = "";

                string user = CommonFunction.GetInitValueByKey("SmtpUser");
                string pwd = CommonFunction.GetInitValueByKey("SmtpPwd");

                if (string.IsNullOrEmpty(user))
                {
                    CommonFunction.ShowMsg("送信者情報は取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpUser未設定");
                    return;
                }
                string mailFrom = CommonFunction.GetInitValueByKey("SmtpFrom");
                if (string.IsNullOrEmpty(mailFrom))
                {
                    CommonFunction.ShowMsg("送信者情報は取得できません。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:SmtpFrom未設定");
                    return;
                }
                string body = txtBody.Text;
                if (string.IsNullOrEmpty(body))
                {
                    CommonFunction.ShowMsg("送信者内容を入力してください。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:txtBody未入力");
                    return;
                }
                string mailTo = txtAddr.Text.Trim();
                if (string.IsNullOrEmpty(mailTo))
                {
                    CommonFunction.ShowMsg("宛先を入力してください。");
                    MyLog.TraceInstance.TraceInformation("frmMail.btnSend:txtAddr未入力");
                    return;
                }

                string mailCC = txtCC.Text.Trim();
                if (string.IsNullOrEmpty(mailCC))
                {
                    mailCC = "";
                }
                SmtpClient smtp = new SmtpClient();

                smtp.Host = host;

                if (!string.IsNullOrEmpty(port))
                {
                    smtp.Port = MyUtils.ParseToInt(port, 0);
                }

                smtp.Credentials = new System.Net.NetworkCredential(user, pwd);

                MailMessage mail = new MailMessage();

                string subject = txtSubject.Text.Trim();

                if (string.IsNullOrEmpty(subject))
                    mail.Subject = "教育指針について";
                else
                    mail.Subject = subject;


                //メールの文字コードを設定
                string encode = CommonFunction.GetInitValueByKey("MailEncode");
                if (!string.IsNullOrEmpty(encode))
                {
                    mail.SubjectEncoding = System.Text.Encoding.GetEncoding(encode);
                    mail.BodyEncoding = System.Text.Encoding.GetEncoding(encode);
                }
                else
                {

                    mail.SubjectEncoding = System.Text.Encoding.GetEncoding("iso-2022-jp");
                    mail.BodyEncoding = System.Text.Encoding.GetEncoding("iso-2022-jp");
                }

                //送信者設定
                mail.From = new MailAddress(mailFrom);

                if (!string.IsNullOrEmpty(ReplyTo))
                    mail.ReplyTo = new MailAddress(ReplyTo);


                if (cmbPriority.Text == "")
                    mail.Priority = MailPriority.Normal;
                else
                    mail.Priority = GetNetMailPriority(cmbPriority.SelectedIndex);



                mail.Body = body;

                mail.To.Add(mailTo);
                if (!string.IsNullOrEmpty(mailCC))
                    //mail.CC.Add(mailCC);
                    mail.Bcc.Add(mailCC);
                if (!string.IsNullOrEmpty(this.lblFileName.Text))
                {
                    if (!string.IsNullOrEmpty(AttachFile))
                    mail.Attachments.Add(new Attachment(AttachFile));
                }
                smtp.Send(mail);


                //メール送信状態更新
                //updateStatus(mondaiid, 1, teacher, address, "");

                this.Close();

            }
            catch (Exception ex)
            {
                CommonFunction.ShowMsg(ex.Message);
                MyLog.TraceInstance.TraceInformation("frmMail.sendMail:" + ex.Message);
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmMail_Load(object sender, EventArgs e)
        {
            try
            {
                string mondaiRUL = "";
                string sMondaiID = mondaiid;
                AttachFile = "";
                // sMondaiID = myEncrypt(sMondaiID) + mondaiid;
                sMondaiID = myEncrypt(sMondaiID);

                if (string.IsNullOrEmpty(sMondaiID))
                    this.Close();
                if (this.cmbPriority.Items.Count > 2)
                    this.cmbPriority.SelectedIndex = 2;
                int i = 0;
                //get Public date
                if (iNendo != 0 && iGrade != 0)
                {
                    using (DBContext db = new DBContext())
                    {
                        SqlResult result = db.CallProcedure("usp_tbSTRPublic_get", iGrade, iNendo);
                        if (result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                        {
                            DataTable dt = result.DataSet.Tables[0];
                            this.PublicStartDate = dt.Rows[0]["dtPublicS"].ToString();
                            this.PublicEndDate = dt.Rows[0]["dtPublicE"].ToString();
                        }
                    }
                }
                //getTeacher name
                if (string.IsNullOrEmpty(address) || string.IsNullOrEmpty(teacher))
                {
                    using (DBContext db = new DBContext())
                    {
                        SqlResult result = db.CallProcedure("uspWebCurriCulumnGetMailInfoEx", mondaiid);
                        if (result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                        {
                            DataTable dt = result.DataSet.Tables[0];
                            this.teacher = dt.Rows[0]["vSyudaisyaName"].ToString();
                            this.address = dt.Rows[0]["vMail"].ToString();
                        }
                    }
                }

                int mondaiRULRow = 0;
                //txtAddr.Text = CommonFunction.GetInitValueByKey("SmtpFrom")
                if (!string.IsNullOrEmpty(address))
                {
                    if (!string.IsNullOrEmpty(teacher))
                        txtAddr.Text = teacher + "<" + address + ">";
                    else
                        txtAddr.Text = address;
                }

                this.txtCC.Text = CommonFunction.GetInitValueByKey("SmtpCC");
                if (CommonFunction.GetInitValueByKey("MailFromTex") == "1")
                {
                    setBodyFromText();
                    return;
                }
                else
                {
                    string strSujuect = CommonFunction.GetInitValueByKey("MailSubject");

                    strSujuect = strSujuect.Replace("#Nendo", iNendo.ToString());
                    strSujuect = strSujuect.Replace("#Grade", iGrade.ToString());
                    strSujuect = strSujuect.Replace("#SubjectName", mondaiNO);
                    txtSubject.Text = strSujuect;

                    string body1 = CommonFunction.GetInitValueByKey("MailBody1");
                    string body2 = CommonFunction.GetInitValueByKey("MailBody2");
                    string body3 = CommonFunction.GetInitValueByKey("MailBody3");
                    string body4 = CommonFunction.GetInitValueByKey("MailBody4");
                    string body5 = CommonFunction.GetInitValueByKey("MailBody5");
                    string body6 = CommonFunction.GetInitValueByKey("MailBody6");
                    mondaiRULRow = MyUtils.ParseToInt(CommonFunction.GetInitValueByKey("URLRow"), 0);
                    string body = "";


                    body = body1;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID + "&gno=" + iGaki.ToString();
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    body = body + Environment.NewLine + body2;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID;
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    body = body + Environment.NewLine + body3;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID;
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID;
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    body = body + Environment.NewLine + body4;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID;
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    body = body + Environment.NewLine + body5;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID;
                        body = body + Environment.NewLine + mondaiRUL;
                    }
                    body = body + Environment.NewLine + body6;
                    i = i + 1;
                    if (i == mondaiRULRow)
                    {
                        mondaiRUL = CommonFunction.GetInitValueByKey("URL") + sMondaiID + "&gno=" + iGaki.ToString();
                        body = body + Environment.NewLine + mondaiRUL;
                    }


                    if (!string.IsNullOrEmpty(teacher))
                    {
                        body = body.Replace("#teacher", teacher);
                    }
                    body = body.Replace("#NewLine", Environment.NewLine);
                    body = body.Replace("#subject", subject);
                    body = body.Replace("#SubjectName", mondaiNO);
                    body = body.Replace("#KaitouRitu", kaitouRitu);
                    body = body.Replace("#mondaiSrc", mondaiSrc);
                    body = body.Replace("#URL", mondaiRUL);
                    body = body.Replace("#Gaki", vGaki);
                    body = body.Replace("#Nendo", iNendo.ToString());
                    body = body.Replace("#Grade", iGrade.ToString());
                    body = body.Replace("#ScoreType", ScoreType);

                    txtBody.Text = body;
                }
            }
            catch (Exception ex)
            {
                CommonFunction.ShowError("frmMail.frmMail_Load", ex.Message);
            }
        }

        private string myEncrypt(string inStr)
        {
            string outStr = "";
            string strTemp;

            strTemp = inStr + "00";
            string str1 = "";
            int i;
            for (i = 1; i <= strTemp.Length; i++)
            {
                str1 = strTemp.Substring(i - 1, 1);
                outStr = outStr + ((char)(((int)str1[0]) + 17)).ToString();

            }
            return outStr;
        }

        private void setBodyFromText()
        {
            try
            {
                string body = "";
                string mondaiRUL = "";
                string title = "";
                string path = "";

                path = Application.StartupPath + @"\mail\" + vGaki + "_Title.txt";
                if (File.Exists(path))
                {
                    StreamReader text = new StreamReader(path, System.Text.Encoding.Default);
                    if (!text.EndOfStream)
                        title = text.ReadToEnd();

                    else
                        title = CommonFunction.GetInitValueByKey("MailSubject");

                    text.Close();
                }
                else
                    title = CommonFunction.GetInitValueByKey("MailSubject");


                title = title.Replace("#Nendo", iNendo.ToString());
                title = title.Replace("#Grade", iGrade.ToString());
                title = title.Replace("#SubjectName", mondaiNO);

                txtSubject.Text = title;

                path = Application.StartupPath + @"\mail\" + vGaki + ".txt";
                if (File.Exists(path))
                {
                    StreamReader text = new StreamReader(path, System.Text.Encoding.Default);
                    if (!text.EndOfStream)
                        body = text.ReadToEnd();
                    text.Close();
                }
                mondaiRUL = CommonFunction.GetInitValueByKey("URL") + mondaiid + "&gno=" + iGaki.ToString();

                body = body.Replace("#URL", mondaiRUL);
                if (!string.IsNullOrEmpty(teacher))
                    body = body.Replace("#Teacher", teacher);

                body = body.Replace("#NewLine", Environment.NewLine);

                body = body.Replace("#SubjectName", mondaiNO);
                body = body.Replace("#KaitouRitu", kaitouRitu);
                body = body.Replace("#mondaiSrc", mondaiSrc);
                body = body.Replace("#Gaki", vGaki);
                body = body.Replace("#Nendo", iNendo.ToString());
                body = body.Replace("#Grade", iGrade.ToString());
                body = body.Replace("#ScoreType", ScoreType);

                body = body.Replace("#PublicStartDate", PublicStartDate);
                body = body.Replace("#PublicEndDate", PublicEndDate);

                txtBody.Text = body;
            }
            catch (Exception ex)
            {
                CommonFunction.ShowError("frmMail.setBodyFromText", ex.Message);
            }
        }

        private void fileLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string fullFilePath = "";
            if (this.openFD.ShowDialog() == DialogResult.OK)
            {
                fullFilePath = this.openFD.FileName;
            }
            string serverPath = CommonFunction.GetInitValueByKey("MailAttachmentPath");
            if (fullFilePath != "")
            {
                try
                {
                    CommonFunction.UpLoadFile(fullFilePath, ref serverPath, false);
                    AttachFile = serverPath;
                    this.lblFileName.Text = fullFilePath;
                }
                catch (Exception ex)
                {
                    CommonFunction.ShowError("fileLink_LinkClicked", ex.Message);
                }
            }
        }

        private void openFD_FileOk(object sender, CancelEventArgs e)
        {
            //if(openFD.hasffi
        }
    }
}
